package com.learn.common.exception;

import com.learn.common.model.AjaxResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class FormValidExceptionHandler{

    @ExceptionHandler(FormValidException.class)
    @ResponseBody
    public AjaxResponse handleAndReturnData(FormValidException ex) {
        AjaxResponse ajaxResponse   =   new AjaxResponse();
        List<FieldError> errors =  ex.getFieldErrors();
        StringBuffer strb = null;
        if(errors != null && errors.size() > 0){
            strb = new StringBuffer("");
            for(FieldError error : errors){
                strb.append(error.getDefaultMessage());
                strb.append("\r\n");
            }
            ajaxResponse.setMessage(strb.toString());
        }
        ajaxResponse.setStatus(false);
        return ajaxResponse;
    }
}
